package mammuthus.template.zookeeper

import mammuthus.protocal.WriteFileTaskResponse
import mammuthus.master.Master
import java.util
import mammuthus.tool.TemplateTool
import mammuthus.template.TemplateProcessor

/**
 * 5/3/15 WilliamZhu(allwefantasy@gmail.com)
 */
class ZooCfgProcessor(master: Master) extends TemplateProcessor {
  override def process(fileName: String, targetFilePath: String, params: Map[String, AnyRef]): List[WriteFileTaskResponse] = {
    val hostNames = params("slaves").asInstanceOf[String]
    val installPath = params("installPath").asInstanceOf[String]
    val appName = params("appName").asInstanceOf[String]
    val app = params.getOrElse("app",appName)
    val idAndHosts = new util.ArrayList[IdAndHost]()
    val host = hostNames.split(",")

    val hostNameToIp = host.map {
      f =>
        (f,master.slaves(f)._2.ip.map(k => k.ipv4).filterNot(k => k == "127.0.0.1")(0))
    }.toMap

    host.sorted.toList.zipWithIndex foreach {
      case (host: String, pos: Int) =>
        idAndHosts.add(new IdAndHost(hostNameToIp(host), pos))
    }
    val configStr = TemplateTool.render(s"/template/app/$app/zoo.cfg.vm", Map(
      "idAndHosts" -> idAndHosts,
      "zkInstallPath" -> s"${installPath}/$appName"
    ))
    master.writeFile(hostNames, configStr, targetFilePath, false).toList
  }
}
